/**
* @file servo.c
* @brief Implementation file for the servo module
*
* This file contains the implementation of the servo module,
* used for controlling the servo motor.
* @作者 Maker Studio
* @license Apache 2.0
* This code is open-sourced under the Apache 2.0 license. When using open-source libraries
* or code, please ensure to acknowledge the original authors and sources.
**/

#include "../inc/servo.h"

/**
 * @brief Initialize the servo motor.
 */
void S92RInit(void)
{
    IoTGpioInit(SERVO_GPIO);
    IoSetFunc(SERVO_GPIO, IOT_IO_FUNC_GPIO_7_GPIO);
    IoTGpioSetDir(SERVO_GPIO, IOT_GPIO_DIR_OUT);
    IoTGpioSetOutputVal(SERVO_GPIO, IOT_GPIO_VALUE0);
}

/**
 * @brief Set the angle of the servo motor.
 * @param duty Duty cycle for the servo motor.
 */
void SetAngle(unsigned int duty)
{
    unsigned int time = FREQ_TIME;

    IoTGpioSetOutputVal(SERVO_GPIO, IOT_GPIO_VALUE1);
    uapi_systick_delay_us(duty);
    IoTGpioSetOutputVal(SERVO_GPIO, IOT_GPIO_VALUE0);
    uapi_systick_delay_us(time - duty);
}

/**
 * @brief Regress the servo motor to the middle position.
 */
void RegressMiddle(void)
{
    unsigned int angle = 1500;
    for (int i = 0; i < COUNT; i++) {
        SetAngle(angle);
    }
}

/**
 * @brief Action to turn on the servo motor.
 */
void ACTION_ON()
{
    unsigned int angle = 2500;
    for (int i = 0; i < COUNT; i++) 
    {
        SetAngle(angle);
    }
}

/**
 * @brief Action to turn off the servo motor.
 */
void ACTION_OFF()
{
    unsigned int angle = 500;
    for (int i = 0; i < COUNT; i++) 
    {
        SetAngle(angle);
    }
}

/**
 * @brief Turn on the light.
 */
void LIGHT_ON()
{
    ACTION_ON();
    RegressMiddle();
}

/**
 * @brief Turn off the light.
 */
void LIGHT_OFF()
{
    ACTION_OFF();
    RegressMiddle();
}
